const gulp = require('gulp');
const sequence = require('gulp-sequence');
const shell = require('gulp-shell');

gulp.task('clean', () => {
	const del = require('del');
	return del('./dist/')
});

gulp.task('compile-ts', shell.task('node --max-old-space-size=4000 "./node_modules/typescript/bin/tsc"'));

gulp.task('watch-ts', shell.task('tsc -w -m umd'));

gulp.task('daoke:build-html-d', () => {
	const through = require('through2');
	const rename = require('gulp-rename');
	const path = require('path');
	const minifyHtml = require("gulp-minify-html");
	return gulp.src('./src/**/html.ts')
		.pipe(rename((file) => {
			const page_no = file.dirname;
			file.basename = page_no;
			file.extname = '.html';
			file.dirname = '../pages';
		}))
		.pipe(through.obj(function (chunk, enc, callback) {
			const page_no = path.basename(chunk.path, '.html');
			const head = Buffer.from(`<!DOCTYPE html>
			<html>

			<head>
				<meta charset="UTF-8">
				<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
				<meta name="format-detection" content="telephone=no">
				<meta name="apple-mobile-web-app-capable" content="yes" />
				<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
				<meta name="renderer" content="webkit">
				<link href="../node_modules/@feidao/css/feidao.css" type="text/css" rel="stylesheet">
				<link rel="stylesheet" type="text/css" href="../css/iconfont.css">
				<link rel="stylesheet" type="text/css" href="../css/daokes.css">
				<script src="../../node_modules/@dojo/loader/loader.js"></script>
				<script type="text/javascript">
					(() => {
						const baseUrl = '../../node_modules/';
						require.config({
							baseUrl: baseUrl,
							packages: [{
								name: 'daoke',
								location: '../dist'
							},{
								name: '@feidao/animation',
								location: '@feidao/animation/umd',
								main: 'index'
							},{
								name: '@feidao/core',
								location: '@feidao/core/umd'
							},{
								name: '@feidao/web',
								location: '@feidao/web/umd'
							},{
								name: '@feidao/widgets',
								location: '@feidao/widgets/umd'
							},{
								name: '@feidao/bscroll',
								location: '@feidao/bscroll/dist',
								main: 'bscroll.js'
							}, {
								name: '@feidao/datepicker.js',
								location: '../node_modules/@feidao/datepicker.js',
								main: 'datepicker'
							},{
								name: 'lodash-ts',
								location: 'lodash-ts/umd'
							},{
								name: 'nools-ts',
								location: 'nools-ts/umd'
							},{
								name: 'dot',
								location: 'dot',
								main: 'doT'
							},{
								name: 'node-html-parser',
								location: 'node-html-parser/dist/umd',
								main: 'index'
							},{
								name: 'javascript-state-machine',
								location: './javascript-state-machine',
								main: 'state-machine'
							},{
								name: 'he',
								location: './he',
								main: 'he.js'
							},{
								name: 'dask',
								location: 'dask/umd',
								main: 'index'
							},{
								name: 'mqtt',
								location: './mqtt/dist',
								main: 'mqtt'
							},{
								name: 'i18next',
								location: './i18next',
								main: 'i18next'
							}, {
								name: 'bootstrap-multiselect',
								location: '../node_modules/bootstrap-multiselect',
								main: 'dist/js/bootstrap-multiselect'
							}]
						});
						window['spaceid'] = 'xmedia';
						require(['daoke/${page_no}/nb'],function(main){
							const url = window.location.href;
							main.default(url).then((res) => {
								document.body.innerHTML = res;
								require(['daoke/${page_no}/b']);
							});
						});
					})();
				</script>
			</head>
			<body>`, 'utf8');
			const tail = Buffer.from(`\n</body></html>`, 'utf8');
			const body = chunk.contents.toString('utf8');
			chunk.contents = Buffer.concat([head, Buffer.from(body.substring(body.indexOf('`') + 1, body.lastIndexOf('`'))), tail]);
			this.push(chunk);
			callback();
		}))
		.pipe(minifyHtml()) // 压缩
		.pipe(gulp.dest('./dist/pages/'));
});

gulp.task('daoke:webpack', (cb) => {
	const dest = './dist/js/';
	const pack_file_path = `./dist/!(zj)*/b.js`;
	const path = require('path');
	const webpack = require('webpack');
	const through = require('through');
	const ws = require('webpack-stream');

	// const commons = new webpack.optimize.CommonsChunkPlugin({
	// 	name: 'feidao',
	// 	minChunks(module, count) {
	// 		return count > 10 || (/state-machine|nools-ts|mqtt|dot|doT|@feidao[\/|\\]/.test(module.request) && !(/@feidao[\/|\\]widgets|@feidao[\/|\\]bscroll|@feidao[\/|\\]animation/.test(module.request)));
	// 	}
	// });
	const ignore = new webpack.IgnorePlugin(/(\.(ts|md)$)|([\/|\\]umd[\/|\\])/);
	gulp.src([pack_file_path])
		.pipe(((opts) => {
			return through(function (file) {
				file.named = path.basename(path.dirname(file.path));
				this.queue(file);
			});
		})())
		.pipe(ws({
			mode: 'production',
			optimization: {
				splitChunks: {
					name: 'feidao',
					chunks: 'all'
				}
			},
			plugins: [ignore],
			externals: [
				// "nools" // this is a bad js file
			],
			output: {
				publicPath: dest
			},
			module: {
				rules: [{
					test: /\.js$/,
					// exclude: /(node_modules|bower_components)/,
					exclude: /core-js|babel/,
					use: {
						loader: 'babel-loader'
					}
				}]
			}
		}, webpack))
		.pipe(gulp.dest(dest));
});

// gulp.start('daoke:webpack');

gulp.task('daoke:browser-sync', () => {
	const browserSync = require('browser-sync').create();
	browserSync.init({
		files: ['./dist/'],
		server: {
			baseDir: "./dist/pages/",
			directory: true
		},
		serveStatic: ['./'],
		port: 8000
	});
});

gulp.task('daoke', ['watch-ts', 'daoke:build-html-d', 'daoke:browser-sync']);

gulp.task('daoke:nodejs', (cb) => {
	const dest = './dist/js';
	const pack_file_path = `./dist/!(zj)*/n.js`;
	const path = require('path');
	const webpack = require('webpack');
	// const babel = require('gulp-babel');
	// const uglyfly = require('gulp-uglify');
	const through = require('through');
	const ws = require('webpack-stream');
	return gulp.src([pack_file_path])
		.pipe(((opts) => {
			return through(function (file) {
				file.named = path.basename(path.dirname(file.path));
				this.queue(file);
			});
		})())
		.pipe(ws({
			mode: 'production',
			module: {
				rules: [{
					test: /\.js$/,
					// exclude: /(node_modules|bower_components)/,
					exclude: /core-js|babel/,
					use: {
						loader: 'babel-loader'
					}
				}]
			}
		}, webpack))
		// .pipe(babel())
		// .pipe(uglyfly())
		.pipe(gulp.dest(dest));
});

gulp.task('build-service', shell.task('tsc --outDir ./dist/js/service/ -p ./service/tsconfig.json'));

gulp.task('daoke-n', sequence('clean', 'compile-ts', 'daoke:nodejs', 'build-service'));

gulp.task('default', sequence('clean', 'compile-ts', 'daoke:webpack'));
